<?php

namespace app\common\model\order;

use app\common\model\Cart;
use app\common\model\goods\category\Region as CategoryRegion;
use app\common\model\goods\Giveaway;
use app\common\model\goods\Goods;
use app\common\model\goods\Region;
use app\common\model\goods\Spec;
use app\common\model\Invoice;
use app\common\model\order\Goods as OrderGoods;
use app\common\model\order\goods\Log;
use app\common\model\User;
use app\common\model\user\Address;
use app\common\model\user\Info;
use think\Db;
use think\Model;


class Order extends Model
{
    // 表名
    protected $name = 'order';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'pay_type_text',
        'paytime_text',
        'createtime_text',
        'order_status_text',
        'sendtime_text',
        'taketime_text',
        'open_invoice',
    ];

    public function getOpenInvoiceAttr($v, $d)
    {
        $invoice = Invoice::get(['order_id' => $d['id'], 'status' => ['<>', '2']]);
        if ($invoice) {
            return false;
        }
        if ($d['taketime']) {
            if (bcadd(config('site.expiration_day') * 86400, $d['taketime'], 0) < time()) {
                return false;
            }
            return true;
        }
        return false;
    }
    static function regionYuOrder($goods_id, $uid, $address_id = 0)
    {

        $goods = Goods::get($goods_id, ['region']);
        //地址信息
        if (isset($address_id) && !empty($address_id)) {
            $addressInfo = Address::get([$address_id]);
            $goods['addressInfo'] = $addressInfo;
            $goods['address_id'] = $address_id;
        } else {
            $addressInfo = Address::getDefaultAddress($uid);
            if ($addressInfo) {
                $goods['addressInfo'] = $addressInfo;
                $goods['address_id'] = $addressInfo['id'];
            }
        }
        $goods['user_id'] = $uid;
        $goods['order_type'] = 2;
        return $goods;
    }
    static function regionAddOrder($param)
    {
        extract($param);
        Db::startTrans();
        try {
            if (!isset($address_id) || !$address_id) {
                exception('收货地址错误');
            }
            $order = [
                'user_id' => $user_id,
                'sn' => sn('order', 'sn', 'NO'),
                'total_num' => 1,
                'total_fee' => $renewal == 1 ? $region['renewal_price'] : $region['price'],
                'address_id' => $address_id,
                'is_yue' => $yue,
                'contact' => $addressInfo['contact'] ?? '',
                'telephone' => $addressInfo['telephone'] ?? '',
                'address' => $addressInfo['province'] . $addressInfo['city'] . $addressInfo['area'] . $addressInfo['address'],
                'receiving_area' => $addressInfo['province'] . '/' . $addressInfo['city'] . '/' . $addressInfo['area'],
                'pay_fee' => $renewal == 1 ? $region['renewal_price'] : $region['price'],
                'order_type' => $order_type,
                'province' => $region['province'],
                'city' => $region['city'],
                'area' => $region['area'],
                'regio' => $region['address'],
                'user_mark' => isset($user_mark) ? $user_mark : '',
                'renewal' => $renewal,
            ];
            $res = Order::create($order, true);
            $userinfo = User::get($user_id);

            if ($status == 'hidden') {
                exception('商品【' . $goods['title'] . '】已下架，不能下单');
            }
            if ($deletetime != null) {
                exception('商品【' . $goods['title'] . '】已删除，不能下单');
            }
            if ($userinfo['region'] != $region['address']) {
                exception('注册区域不匹配');
            }
            if ($renewal == 1) {
                $renewal_period = config('site.renewal_period');
                if ($renewal_period > 0) {
                    $info = Info::get(['region_id' => $region_id, 'user_id' => $user_id]);
                    if ($info) {
                        if ($renewal_period < $info->end_day) {
                            exception("提前" . $renewal_period . "天续费");
                        }
                    }
                }
            } else {
                $info = Info::get(['region_id' => $region_id, 'user_id' => $user_id]);
                if ($info) {
                    exception("已开通该区域");
                }
            }
            if ($region['num'] > 0) {
                $infoCount = Info::where([
                    'region_id' => $region_id,
                ])->count();
                if ($infoCount >= $region['num']) {
                    exception('区域代理已存在');
                }
            } else {
                exception('区域未授权');
            }

            $giveaway = Giveaway::get(['goods_id' => $id]);
            $total_price = round($region['price'], 2);
            $data = [
                'order_id' => $res->id,
                'goods_id' => $id,
                'goods_num' => 1,
                'goods_name' => $title,
                'goods_type' => $type,
                'region_id' => $region_id,
                'goods_price' =>  $renewal == 1 ? $region['renewal_price'] : $region['price'],
                'total_price' => $total_price,
                'image' => $image,
                'pay_fee' => $renewal == 1 ? $region['renewal_price'] : $region['price'],
                'spec_info' => json_encode($param),
                'giveaway_info' => json_encode($giveaway),
                'first_cate' => $first_cate,
                'two_cate' => $two_cate,
            ];
            OrderGoods::create($data);
            $goods = Goods::get($id);
            $goods->setInc('sales', 1);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            exception($e->getMessage());
        }
        return $res->id;
    }
    static function yuOrder($cart_ids, $uid, $address_id = 0, $region_id = 0, $type = 1)
    {

        $goodsList = collection(Cart::with(['spec', 'goods'])->whereIn('cart.id', $cart_ids)->select())->toArray();
        $total_fee = $original_price = $pay_fee = 0;
        $is_yue = 0;
        $order_type = 1;
        foreach ($goodsList as $k => &$v) {
            $goods = $v['goods'];
            if ($goods['yue'] == 1) {
                $is_yue = 1;
            }
            if ($type == 1 && $goods['type'] == 2) {
                Cart::where('id', $v['id'])->delete();
                unset($k);
                continue;
            }
            if ($goods['type'] == 2) {
                $order_type = 2;
                $region = Region::get($region_id);
                $province = $region['province'];
                $city = $region['city'];
                $area = $region['area'];
                $address = $region['address'];
            }
            $product = $v['spec'];
            Spec::checkGoods($v);
            $total_fee += bcmul($product['price'], $v['num'], 2);
            $original_price += bcmul($product['original_price'], $v['num'], 2);
        }
        //地址信息
        if (isset($address_id) && !empty($address_id)) {
            $addressInfo = Address::get([$address_id]);
            $data['addressInfo'] = $addressInfo;
            $data['address_id'] = $address_id;
        } else {
            $addressInfo = Address::getDefaultAddress($uid);
            if ($addressInfo) {
                $data['addressInfo'] = $addressInfo;
                $data['address_id'] = $addressInfo['id'];
            }
        }
        $data['goodsList'] = $goodsList;
        $data['total_num'] = array_sum(array_column($goodsList, 'num'));
        $data['total_fee'] = round($total_fee, 2);
        $data['pay_fee'] = round($total_fee, 2);
        $data['user_id'] = $uid;
        $data['cart_ids'] = $cart_ids;
        $data['order_type'] = $order_type;
        $data['is_yue'] = $is_yue;
        $data['province'] = isset($province) ? $province : '';
        $data['city'] = isset($city) ? $city : '';
        $data['area'] = isset($area) ? $area : '';
        $data['address'] = isset($address) ? $address : '';
        $data['region_id'] = $region_id;
        return $data;
    }
    static function addOrder($param)
    {
        extract($param);
        Db::startTrans();
        try {
            if (!isset($address_id) || !$address_id) {
                exception('收货地址错误');
            }
            if (!isset($total_num) || $total_num <= 0) {
                exception('购买数量错误');
            }
            $order = [
                'user_id' => $user_id,
                'sn' => sn('order', 'sn', 'NO'),
                'total_num' => $total_num,
                'total_fee' => $total_fee,
                'address_id' => $address_id,
                'is_yue' => $is_yue,
                'contact' => $addressInfo['contact'] ?? '',
                'telephone' => $addressInfo['telephone'] ?? '',
                'address' => $addressInfo['province'] . $addressInfo['city'] . $addressInfo['area'] . $addressInfo['address'],
                'receiving_area' => $addressInfo['province'] . '/' . $addressInfo['city'] . '/' . $addressInfo['area'],
                'pay_fee' => $pay_fee,
                'order_type' => $order_type,
                'province' => $province,
                'city' => $city,
                'area' => $area,
                'regio' => $address,
                'user_mark' => isset($user_mark) ? $user_mark : '',
            ];
            $res = Order::create($order, true);
            $userinfo = User::get($user_id);
            foreach ($goodsList as $v) {
                Spec::checkGoods($v);
                $info = Info::get([
                    'first_cate' => $v['goods']['first_cate'],
                    'two_cate' => $v['goods']['two_cate'],
                    'user_id' => $user_id,
                ]);
                if ($v['goods']['pay_auth'] == 1) {
                    if ($userinfo['group_id'] <= 1) {
                        exception('没有购买权限，需升级身份购买');
                    }
                    $region = CategoryRegion::where('category_id', $v['goods']['two_cate'])->count();
                    if ($region) {
                        if (!$info) {
                            exception('没有购买权限，需升级身份购买');
                        }
                    }
                }
                $product = Spec::get($v['spec_id']);
                $giveaway = Giveaway::get(['goods_id' => $v['goods_id']]);
                $total_price = bcmul($v['spec']['price'], $v['num'], 2);

                $data = [
                    'order_id' => $res->id,
                    'user_id' => $user_id,
                    // 'logs_ids' => implode(',', $uids),
                    'goods_id' => $v['goods_id'],
                    'spec_id' => $v['spec_id'],
                    'goods_num' => $v['num'],
                    'goods_name' => $v['goods']['title'],
                    'goods_type' => $v['goods']['type'],
                    'region_id' => $region_id,
                    'goods_price' => $v['spec']['price'],
                    'total_price' => $total_price,
                    'image' => $v['goods']['image'],
                    'pay_fee' => $total_price,
                    'spec_info' => json_encode($product),
                    'giveaway_info' => json_encode($giveaway),
                    'first_cate' => $v['goods']['first_cate'],
                    'two_cate' => $v['goods']['two_cate'],
                ];
                OrderGoods::create($data);
                Spec::reduceInventory($v['goods_id'], $v['spec_id'], $v['num']);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            exception($e->getMessage());
        }
        return $res->id;
    }
    static function yu_renew($data)
    {
        extract($data);
        $info = Info::get($info_id);
        $goods = Goods::get(['region_id' => $info->region_id, 'renewal' => 1], ['region']);
        if (!$goods) {
            exception('续费商品不存在，暂时无法续费，请联系客服');
        }
        //地址信息
        if (isset($address_id) && !empty($address_id)) {
            $addressInfo = Address::get([$address_id]);
            $goods['addressInfo'] = $addressInfo;
            $goods['address_id'] = $address_id;
        } else {
            $addressInfo = Address::getDefaultAddress($uid);
            if ($addressInfo) {
                $goods['addressInfo'] = $addressInfo;
                $goods['address_id'] = $addressInfo['id'];
            }
        }

        $goods['user_id'] = $uid;
        $goods['order_type'] = 2;
        return $goods;
    }
    public function getSettleList()
    {
        return [0 => '未结算', '1' => __('已结算')];
    }
    public function getPayTypeList()
    {
        return ['' => __(''), '1' => __('Pay_type 1'), '2' => __('Pay_type 2'), '3' => __('Pay_type 3'), '4' => __('Pay_type 4'), '5' => __('Pay_type 5')];
    }

    public function getOrderStatusList()
    {
        return ['0' => __('Order_status 0'), '10' => __('Order_status 10'), '20' => __('Order_status 20'), '30' => __('Order_status 30'),  '-1' => __('Order_status -1')];
    }


    public function getPayTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['pay_type']) ? $data['pay_type'] : '');
        $list = $this->getPayTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }
    public function getCreatetimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['createtime']) ? $data['createtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getPaytimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['paytime']) ? $data['paytime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getOrderStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['order_status']) ? $data['order_status'] : '');
        $list = $this->getOrderStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function setCreatetimeAttr($value, $data)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }
    public function getTaketimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['taketime']) ? $data['taketime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getSendtimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['sendtime']) ? $data['sendtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setPaytimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setSendtimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    public function goods()
    {
        return $this->hasMany(OrderGoods::class, 'order_id', 'id');
    }
    public function user()
    {
        return $this->belongsTo('app\common\model\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function address()
    {
        return $this->belongsTo('app\common\model\user\Address', 'address_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    static function check_goods($param)
    {

        extract($param);
        try {
            $data['num'] = $num;
            $data['spec'] = Spec::get($spec_id);
            $data['goods'] = Goods::get($spec['goods_id']);
            Spec::checkGoods($data);
        } catch (\Exception $e) {
            exception($e->getMessage());
        }
    }
}
